﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        ircClient client;
        string incomingText;
        StreamWriter logger; 
        public Form1()
        {
            InitializeComponent();
            this.ActiveControl = textBox2;
            client = new ircClient();
            logger = new StreamWriter("irc.log", true);
            logger.AutoFlush = true;
            incomingText = "";

            writeIncomingData("Welcome to the RuIRC client! " + Environment.NewLine + "For a list of commands type /commands");

        }
        

     

        //Fall fyrir threading svo það er hægt að interactea við föll úr mismunandi þráðum
        public delegate void UpdateTextCallback(string message);

        //Fall sem keyrir endalaust og prentar út message sem irc clientinn hefur fengið
        private void loop()
        {
            while (true)
            {
                Thread.Sleep(2);
                if (client.getText(ref incomingText) > 0)
                {
                    textBox1.BeginInvoke(new UpdateTextCallback(writeIncomingData), new object[]{
                        incomingText});
                }
            }
        }

        //Skrifar út á aðal textasvæðið, þarf að athuga með að birta mismundi skilaoð í mismunandi gluggum
        private void writeIncomingData(string text)
        {
            //textBox1.Text += text + "\r\n";
            textBox1.AppendText(text + Environment.NewLine);
            
            logger.WriteLine(DateTime.Now + ":"+text);
            //Stop the scrollbar from jumping up on new line
            textBox1.Select(textBox1.Text.Length - 1, 1);
            textBox1.ScrollToCaret();

        }
        
        //Detects the Enter keypress and sends the commands onwards for parsing.
        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (int)Keys.Enter)
            {
                parseCommand(textBox2.Text);
                //client.sendMessage(textBox2.Text);
                textBox2.Text = "";
            }
           
        }

        

        //Parses the commands entered into the command line
        private void parseCommand(string command)
        {
            if (command.StartsWith("/"))
            {
                command = command.Replace("/", "");
                command = command.ToLower();
               
                if(command.StartsWith("nick"))
                {
                    string[] parameters;
                    char[] splitchar = { ' ' };
                    parameters = command.Split(splitchar);
                    client.sendMessage("NICK " + parameters[1]);
                }

                if (command.StartsWith("join"))
                {
                    string[] parameters;
                    char[] splitchar = { ' ' };
                    parameters = command.Split(splitchar);
                    client.sendMessage("JOIN " + parameters[1]);
                    
                }

                //Parse the list command
                if(command.StartsWith("commands"))
                {
                    writeIncomingData(Environment.NewLine + "/server <server name> <port>    -Connect to a server"
                        + Environment.NewLine + "/commands   -See a list of available commands"
                        + Environment.NewLine + "/nick <name>   -Change your nickname"
                        + Environment.NewLine + "/join <#channel>   -Join a channel"
                        + Environment.NewLine + "/quit   -Quit the RuIRC client");
                }

                //Parse the quit command
                if(command.StartsWith("quit"))
                {
                    client.sendMessage("QUIT"); 
                    //quit();
                }

                if (command.StartsWith("server"))
                {
                    string[] parameters;
                    char[] splitchar = { ' ' };
                    parameters = command.Split(splitchar);
                    try
                    {
                        connectClient(parameters[1], Int32.Parse(parameters[2]));
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                        writeIncomingData("To connect to a server use: /server <server name> <port>");
                    }

                }
                /*
                if (!client.isConnected())
                {
                    
                    if (command.StartsWith("server"))
                    {
                        string[] parameters;
                        char[] splitchar = { ' ' };
                        parameters = command.Split(splitchar);

                        try
                        {
                            connectClient(parameters[1], Int32.Parse(parameters[2]));
                        }
                        catch(Exception e)
                        {
                            Debug.WriteLine(e.Message);
                            writeIncomingData("To connect to a server use: /server <server name> <port>");
                        }
                        
                    }
                    else
                    {
                        writeIncomingData("Not connected to a server");
                    }
                }
                else 
                {
                    client.sendMessage(command); //If no match was found then we send the message as is
                }*/
            }
            else
            {
                client.sendMessage(command); //If no match was found then we send the message as is
            }
            //textBox1.AppendText(command + Environment.NewLine);
        }

        private void connectClient(string server, int port)
        {
            client.connect(server,port);
            Thread listener = new Thread(loop);
            listener.Start();
        }

        private void quit()
        {
            Application.Exit();
        }

        private void quitThread()
        {
            Application.ExitThread();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            parseCommand(textBox2.Text);
            //client.sendMessage(textBox2.Text);
            textBox2.Text = "";
        }
    }
}
